package com.castle.fortress.admin.jmreport.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.jmreport.dto.CastleJmrAuditDto;
import com.castle.fortress.admin.jmreport.entity.CastleJmrAuditEntity;
import com.castle.fortress.admin.jmreport.entity.JimuReportEntity;
import com.castle.fortress.admin.jmreport.dto.JimuReportDto;
import com.castle.fortress.admin.jmreport.service.CastleJimuReportService;
import com.castle.fortress.admin.jmreport.service.CastleJmrAuditService;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;
import javax.servlet.http.HttpServletResponse;
import com.castle.fortress.common.entity.DynamicExcelEntity;

import java.util.Date;
import java.util.List;

/**
 * 在线excel设计器 控制器
 *
 * @author castle
 * @since 2023-10-11
 */
@Api(tags="在线excel设计器管理控制器")
@Controller
public class JimuReportController {
    @Autowired
    private CastleJimuReportService castleJimuReportService;
    @Autowired
    private CastleJmrAuditService castleJmrAuditService;

    /**
     * 查看当前用户自己创建的或者是可见范围内的
     * 管理员查看所有
     * @param jimuReportDto 在线excel设计器实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.QUERY)
    @ApiOperation("在线excel设计器分页展示")
    @GetMapping("/castlejmreport/jimuReport/page")
    @ResponseBody
    @RequiresPermissions("jmreport:jimuReport:pageList")
    public RespBody<IPage<JimuReportDto>> pageJimuReport(JimuReportDto jimuReportDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        SysUser user = WebUtil.currentUser();
        if(user==null){
            throw new BizException(GlobalRespCode.UNAUTHORIZED);
        }
        Page<JimuReportDto> page = new Page(pageIndex, pageSize);
        IPage<JimuReportDto> pages = castleJimuReportService.pageJimuReport(page, jimuReportDto,user);
        return RespBody.data(pages);
    }

    /**
     * 在线excel设计器的列表展示
     * @param jimuReportDto 在线excel设计器实体类
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.QUERY)
    @ApiOperation("在线excel设计器列表展示")
    @GetMapping("/castlejmreport/jimuReport/list")
    @ResponseBody
    public RespBody<List<JimuReportDto>> listJimuReport(JimuReportDto jimuReportDto){
        List<JimuReportDto> list = castleJimuReportService.listJimuReport(jimuReportDto);
        return RespBody.data(list);
    }

    /**
     * 在线excel设计器保存
     * @param jimuReportDto 在线excel设计器实体类
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.INSERT)
    @ApiOperation("在线excel设计器保存")
    @PostMapping("/castlejmreport/jimuReport/save")
    @ResponseBody
    @RequiresPermissions("jmreport:jimuReport:save")
    public RespBody<String> saveJimuReport(@RequestBody JimuReportDto jimuReportDto){
        SysUser user = WebUtil.currentUser();
        if(user==null){
            throw new BizException(GlobalRespCode.UNAUTHORIZED);
        }
        if(jimuReportDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        Long id = IdWorker.getId();
        jimuReportDto.setId(id+"");
        jimuReportDto.setDelFlag(false);
        jimuReportDto.setTemplate(false);
        jimuReportDto.setCreateBy(user.getLoginName());
        jimuReportDto.setCreateTime(new Date());
        jimuReportDto.setCode(System.currentTimeMillis()+"");
        jimuReportDto.setViewCount(0l);
        JimuReportEntity jimuReportEntity = ConvertUtil.transformObj(jimuReportDto,JimuReportEntity.class);
        if(castleJimuReportService.save(jimuReportEntity)){
            if(jimuReportDto.getCastleJmrAuditDto()!=null){
                CastleJmrAuditDto auditDto = jimuReportDto.getCastleJmrAuditDto();
                auditDto.setJmrId(id+"");
                castleJmrAuditService.save(ConvertUtil.transformObj(auditDto, CastleJmrAuditEntity.class));
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 在线excel设计器编辑
     * @param jimuReportDto 在线excel设计器实体类
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("在线excel设计器编辑")
    @PostMapping("/castlejmreport/jimuReport/edit")
    @ResponseBody
    @RequiresPermissions("jmreport:jimuReport:edit")
    public RespBody<String> updateJimuReport(@RequestBody JimuReportDto jimuReportDto){
        SysUser user = WebUtil.currentUser();
        if(user==null){
            throw new BizException(GlobalRespCode.UNAUTHORIZED);
        }
        if(jimuReportDto == null || jimuReportDto.getId() == null || jimuReportDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        JimuReportEntity entity = castleJimuReportService.getById(jimuReportDto.getId());
        if(entity==null){
            throw new BizException(GlobalRespCode.BUSINESS_ERROR);
        }
        QueryWrapper<CastleJmrAuditEntity> wrapper = new QueryWrapper();
        wrapper.eq("jmr_id",entity.getId());
        castleJmrAuditService.remove(wrapper);
        //只允许修改名称、说明、类型、缩略图
        entity.setName(jimuReportDto.getName());
        entity.setNote(jimuReportDto.getNote());
        entity.setType(jimuReportDto.getType());
        entity.setThumb(jimuReportDto.getThumb());
        entity.setUpdateBy(user.getLoginName());
        entity.setUpdateTime(new Date());
        if(castleJimuReportService.updateById(entity)){
            if(jimuReportDto.getCastleJmrAuditDto()!=null){
                CastleJmrAuditDto auditDto = jimuReportDto.getCastleJmrAuditDto();
                auditDto.setJmrId(entity.getId());
                castleJmrAuditService.save(ConvertUtil.transformObj(auditDto, CastleJmrAuditEntity.class));
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 在线excel设计器删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.DELETE)
    @ApiOperation("在线excel设计器删除")
    @PostMapping("/castlejmreport/jimuReport/delete")
    @ResponseBody
    @RequiresPermissions("jmreport:jimuReport:delete")
    public RespBody<String> deleteJimuReport(@RequestParam String id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(castleJimuReportService.delById(id)) {
            QueryWrapper<CastleJmrAuditEntity> wrapper = new QueryWrapper();
            wrapper.eq("jmr_id",id);
            castleJmrAuditService.remove(wrapper);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 在线excel设计器批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.DELETE)
    @ApiOperation("在线excel设计器批量删除")
    @PostMapping("/castlejmreport/jimuReport/deleteBatch")
    @ResponseBody
    @RequiresPermissions("jmreport:jimuReport:deleteBatch")
    public RespBody<String> deleteJimuReportBatch(@RequestBody List<String> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(castleJimuReportService.delByIds(ids)) {
            QueryWrapper<CastleJmrAuditEntity> wrapper = new QueryWrapper();
            wrapper.in("jmr_id",ids);
            castleJmrAuditService.remove(wrapper);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 在线excel设计器详情
     * @param id 在线excel设计器id
     * @return
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.QUERY)
    @ApiOperation("在线excel设计器详情")
    @GetMapping("/castlejmreport/jimuReport/info")
    @ResponseBody
    @RequiresPermissions("jmreport:jimuReport:info")
    public RespBody<JimuReportDto> infoJimuReport(@RequestParam String id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        JimuReportEntity jimuReportEntity = castleJimuReportService.getById(id);
        JimuReportDto jimuReportDto = ConvertUtil.transformObj(jimuReportEntity,JimuReportDto.class);
        if(jimuReportDto!=null){
            QueryWrapper<CastleJmrAuditEntity> wrapper = new QueryWrapper();
            wrapper.in("jmr_id",id);
            List<CastleJmrAuditEntity> entities = castleJmrAuditService.list(wrapper);
            if(entities!=null && entities.size()>0){
                jimuReportDto.setCastleJmrAuditDto(ConvertUtil.transformObj(entities.get(0),CastleJmrAuditDto.class));
            }
        }
        return RespBody.data(jimuReportDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="在线excel设计器",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/castlejmreport/jimuReport/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<JimuReportDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<JimuReportDto> list = castleJimuReportService.listJimuReport(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
